//
//  CZEmotionTools.swift
//  WeiBO28
//
//  Created by 飞奔的羊 on 16/5/21.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
//读取表情数据专用类
class CZEmotionTools: NSObject {
	//单例全局访问点
	static let sharedTools: CZEmotionTools = CZEmotionTools()
	//构造函数私有化
	private override init() {
		super.init()
//		print(defaultEmticons.count)
//		print(emojiEmticons.count)
	}
	
	//创建 emoticon bundle 对象,因为资源都在这个 bundle 里面
	private lazy var emoticonBunle: NSBundle = {
	let path = NSBundle.mainBundle().pathForResource("Emoticons.bundle", ofType: nil)!
	//创建 bundle 对象
		let bundle = NSBundle(path: path)!
		///返回 bundle 对象
		return bundle
	}()
	// 读取默认表情
	private lazy var defaultEmticons: [CZEmoticon] = {
	return self.loadEmoticonWithPath("default/info.plist")
	}()
	// 读取emoji表情
	private lazy var emojiEmticons: [CZEmoticon] = {
		return self.loadEmoticonWithPath("emoji/info.plist")
	}()

	// 读取 浪小花表情
	private lazy var LxhEmticons: [CZEmoticon] = {
		return self.loadEmoticonWithPath("lxh/info.plist")
	}()
//准备数据
	 lazy var allEmoticons: [[[CZEmoticon]]] = {
	
		return [
		 self.sectionWithEmoticons(self.defaultEmticons),
		self.sectionWithEmoticons(self.emojiEmticons),
		self.sectionWithEmoticons(self.LxhEmticons)
		
		]
	}()
	private func loadEmoticonWithPath(subPath: String)->[CZEmoticon] {
		let path = self.emoticonBunle.pathForResource(subPath, ofType: nil)!
		//加载 plist 资源数据
		let array = NSArray(contentsOfFile: path)!
	 var tempArr = [CZEmoticon]()
		for dic in array
		{
			let emoticon = CZEmoticon(dic: dic as! [String: AnyObject])
	//判断是否是图片
			if emoticon.type == "0" {
    //给 Path 拼接路径
				//获取图片名字
				let png = emoticon.png!
				//吧路径里面的最后一部分干掉
				let subPath = (path as NSString).stringByDeletingLastPathComponent
				emoticon.path = subPath + "/"  + png
			}
			
			tempArr.append(emoticon)
		}
		
		
		return tempArr
	
	}
	 func emoticonWithEMoticonStr(emoticonStr: String) -> CZEmoticon? {
	 for value in defaultEmticons
		{
			if value.chs == emoticonStr {
    return value
			}
		}
	 for value in LxhEmticons
		{
			if value.chs == emoticonStr {
    return value
			}
		}
		return nil
	}
	
	///截取计算页数数据
	private func sectionWithEmoticons(emoticons: [CZEmoticon]) -> [[CZEmoticon]]{
		//计算页数
		let pageCount = (emoticons.count - 1) / 20 + 1
		
		var tempArray: [[CZEmoticon]] = [[CZEmoticon]]()
		//遍历页数,计算截取
		for i in 0..<pageCount
		{//计算当前截图的缩影
			let locaction = i * 20
			var length = 20
			//如果是户主越界,重新计算数组长度
			if locaction + length > emoticons.count {
    length = emoticons.count - locaction
			}
			
		let subArray = (emoticons as NSArray).subarrayWithRange(NSMakeRange(locaction, length))as! [CZEmoticon]
		tempArray.append(subArray)
		
		}
		return tempArray
		
	}
	
}
























